package com.sunfeng.chap2;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @Author : 孙峰
 * @Description: 使用多个线程同时对 FileChannel 通道进行写入，并且 int write(ByteBuffer src）方法彼此之间出现同步的效果
 *
 *  说明 write 方法是同步的
 *
 * @Date : 2021/10/8  14:33
 */
public class Test1_3 {
    private static FileOutputStream fosRef ;
    private static FileChannel fileChannel;
    public static void main(String[] args) throws IOException, InterruptedException {
         fosRef = new FileOutputStream(new File("D:\\a.txt"));
         fileChannel = fosRef.getChannel();
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    ByteBuffer buffer = ByteBuffer.wrap("abcdf\r\n".getBytes(StandardCharsets.UTF_8));
                    try {
                        fileChannel.write(buffer);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
            Thread thread2 = new Thread() {
                @Override
                public void run() {
                    ByteBuffer buffer = ByteBuffer.wrap("我是中国人\r\n".getBytes(StandardCharsets.UTF_8));
                    try {
                        fileChannel.write(buffer);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
            thread.start();
            thread2.start();
        }
        TimeUnit.SECONDS.sleep(3);
        fileChannel.close();
        fosRef.close();
    }
}
